package com.jinmdz.fmis.api.admin.service;

import com.jinmdz.fmis.api.admin.model.equipment.EquipmentIdData;
import com.jinmdz.fmis.api.admin.model.equipment.EquipmentListData;
import com.jinmdz.fmis.api.admin.model.equipment.EquipmentLoadData;
import com.jinmdz.fmis.api.admin.model.equipment.EquipmentSaveData;
import com.jinmdz.fmis.api.api.model.common.IdVersionData;
import com.jinmdz.fmis.api.api.service.DictionaryService;
import com.jinmdz.fmis.api.base.BaseService;
import com.jinmdz.fmis.api.model.config.dictionary.OperationLogCode;
import com.jinmdz.fmis.api.model.system.UserItem;
import com.jinmdz.fmis.api.wrapper.DictionaryWrapper;
import com.jinmdz.fmis.api.wrapper.OperationWrapper;
import com.jinmdz.fmis.common.ext.StringBuilderExt;
import com.jinmdz.fmis.common.util.BeanUtil;
import com.jinmdz.fmis.common.util.DataUtil;
import com.jinmdz.fmis.core.base.BasePageData;
import com.jinmdz.fmis.core.base.BaseResult;
import com.jinmdz.fmis.core.constant.EDictCode;
import com.jinmdz.fmis.core.exception.ActionException;
import com.jinmdz.fmis.core.model.SearchLoadData;
import com.jinmdz.fmis.core.util.JacksonUtil;
import com.jinmdz.fmis.dao.admin.dao.EquipmentDao;
import com.jinmdz.fmis.dao.admin.model.equipment.EquipmentEditItem;
import com.jinmdz.fmis.dao.admin.model.equipment.EquipmentListItem;
import com.jinmdz.fmis.dao.dao.ServiceItemDao;
import com.jinmdz.fmis.dao.model.dictionary.ServiceDictionaryRuleItem;
import com.jinmdz.fmis.mapper.entity.ColdStorageEquipmentEntity;
import com.jinmdz.fmis.mapper.mapper.ColdStorageEquipmentMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 冷藏冷柜Service
 *
 * @author LiCongLu
 * @date 2020-03-11 11:16
 */
@Service("equipmentService")
public class EquipmentService extends BaseService {

    @Resource
    private EquipmentDao equipmentDao;

    @Resource
    private DictionaryWrapper dictionaryWrapper;

    @Resource
    private ColdStorageEquipmentMapper coldStorageEquipmentMapper;

    @Resource
    private OperationWrapper operationWrapper;

    @Resource
    private OperationLogCode operationLogCode;

    @Resource
    private ServiceItemDao serviceItemDao;

    @Resource
    private DictionaryService dictionaryService;

    /**
     * 加载冷藏冷柜信息
     *
     * @param data 分页条件
     * @return
     * @author LiCongLu
     * @date 2020-03-11 11:17
     */
    public BaseResult<SearchLoadData<EquipmentListData>> loadEquipmentList(BasePageData data) {
        // 初始化分页数据
        startPageData(data);
        ArrayList<EquipmentListItem> loadItems = equipmentDao.listEquipmentList();

        // 进行分页处理
        SearchLoadData<EquipmentListItem> searchData = getSearchLoadData(loadItems);
        // 处理分页后信息
        ArrayList<EquipmentListData> dataList = loadEquipmentListData(searchData.getList());

        // 重新返回分页信息
        SearchLoadData<EquipmentListData> loadData = new SearchLoadData<>();
        loadData.setList(dataList)
                .setPager(searchData.getPager());
        return successData(loadData);
    }

    /**
     * 加载冷藏冷柜信息
     *
     * @param
     * @return
     * @author LiCongLu
     * @date 2020-03-11 11:17
     */
    public BaseResult<ArrayList<EquipmentListData>> loadEquipmentPreviewList() {
        ArrayList<EquipmentListItem> loadItems = equipmentDao.listEquipmentList();
        ArrayList<EquipmentListData> dataList = loadEquipmentListData(loadItems);
        return successList(dataList);
    }

    /**
     * 处理查询结果
     *
     * @param loadItems 加载数据
     * @return
     * @author LiCongLu
     * @date 2020-03-13 15:37
     */
    private ArrayList<EquipmentListData> loadEquipmentListData(List<EquipmentListItem> loadItems) {

        // 设置字典文本
        dictionaryWrapper.resetDataText(loadItems);

        // 加载服务规则
        String dictCode = EDictCode.EQUIPMENT_TYPE.getCode();
        // 获取全部规则
        ArrayList<ServiceDictionaryRuleItem> ruleAllItems = serviceItemDao.listServiceDictionaryRuleByDictCode(dictCode, "");

        // 返回数据
        ArrayList<EquipmentListData> dataList = BeanUtil.copy2List(loadItems, EquipmentListData.class);

        for (EquipmentListData listData : dataList) {
            ArrayList<ServiceDictionaryRuleItem> ruleItems = new ArrayList<>();
            ruleAllItems.forEach(ruleItem -> {
                // 判断数据结构
                if (DataUtil.equals(ruleItem.getDataCode(), listData.getEquipmentTypeCode())) {
                    ruleItems.add(ruleItem);
                }
            });
            listData.setRuleItems(ruleItems);
        }
        return dataList;
    }

    /**
     * 加载冷藏冷柜信息
     *
     * @param data 冷藏冷柜主键
     * @return
     * @author LiCongLu
     * @date 2020-03-11 11:17
     */
    public BaseResult<EquipmentLoadData> loadEquipmentWithId(EquipmentIdData data) {
        // 加载数据
        EquipmentLoadData loadData = new EquipmentLoadData();

        // 加载数据
        if (DataUtil.valid(data.getId())) {
            Integer loadId = data.getId();
            // 查询信息
            EquipmentEditItem loadItem = equipmentDao.getEquipmentEditById(loadId);
            if (DataUtil.isNull(loadItem) || DataUtil.isNull(loadItem.getId(), loadItem.getVersion())) {
                return failure("主键错误，不存在此冷藏冷柜信息");
            }
            loadData.setEquipment(BeanUtil.copy2Bean(loadItem, new EquipmentSaveData()));
        }

        // 加载字典数据
        loadData.setDicts(dictionaryService.loadDictionaryMap(data.getDictTypeCodes()));

        // 加载服务规则
        String dictCode = EDictCode.EQUIPMENT_TYPE.getCode();
        loadData.setRuleItems(serviceItemDao.listServiceDictionaryRuleByDictCode(dictCode, ""));

        // 返回响应结果
        return successData(loadData);
    }

    /**
     * 保存冷藏冷柜信息
     *
     * @param userItem 当前帐号
     * @param data     请求数据
     * @return
     * @author LiCongLu
     * @date 2020-03-11 11:18
     */
    @Transactional(rollbackFor = Exception.class)
    public BaseResult saveEquipment(UserItem userItem, EquipmentSaveData data) throws ActionException {
        Integer id = data.getId();
        // 主键不为空
        if (DataUtil.valid(id)) {
            updateEquipment(userItem, data);
        } else {
            id = insertEquipment(userItem, data);
        }
        return success("保存成功");
    }

    /**
     * 插入冷藏冷柜信息
     *
     * @param userItem 当前帐号
     * @param data     请求数据
     * @return
     * @author LiCongLu
     * @date 2020-03-11 11:18
     */
    private Integer insertEquipment(UserItem userItem, EquipmentSaveData data) throws ActionException {
        // 创建实体
        ColdStorageEquipmentEntity entity = getEntity(userItem, ColdStorageEquipmentEntity.class);

        // 覆盖数据
        BeanUtil.copy2Bean(data, entity);

        // 对冷藏冷柜信息进行判断处理
        checkEquipmentValue(entity);

        // 新增冷藏冷柜信息
        coldStorageEquipmentMapper.insertColdStorageEquipment(entity);
        // 判断保存冷藏冷柜信息结果
        if (DataUtil.invalid(entity.getId())) {
            throw exception("保存冷藏冷柜信息失败");
        }

        // 添加操作日志
        saveEquipmentLog(userItem, operationLogCode.getInsert(), data, null, entity);
        return entity.getId();
    }

    /**
     * 验证处理冷藏冷柜信息
     *
     * @param entity 冷藏冷柜信息
     * @return
     * @author LiCongLu
     * @date 2020-03-11 11:19
     */
    public void checkEquipmentValue(ColdStorageEquipmentEntity entity) throws ActionException {

        // 判断禁用状态
        if (DataUtil.isNull(entity.getDisableState())) {
            entity.setDisableState(0);
        }

        // 设置状态值
        if (DataUtil.isNull(entity.getEquipmentState())) {
            entity.setEquipmentState(0);
        }

        // 判断排序值
        if (DataUtil.isNull(entity.getSort())) {
            entity.setSort(0);
        }

        // 判断冷藏冷柜编号的重复性
        Integer equipmentCodeId = equipmentDao.getEquipmentIdByEquipmentCode(entity.getId(), entity.getEquipmentCode());
        if (DataUtil.valid(equipmentCodeId)) {
            throw exception("存在重复的冷藏冷柜编号");
        }
    }

    /**
     * 添加冷藏冷柜修改记录
     *
     * @param userItem    当前帐号
     * @param logTypeCode 操作日志值
     * @param data        请求数据
     * @param oldValue    旧数据
     * @param entity      保存实体
     * @return
     * @author LiCongLu
     * @date 2020-03-11 11:20
     */
    private void saveEquipmentLog(UserItem userItem, Integer logTypeCode, EquipmentSaveData data, String oldValue, ColdStorageEquipmentEntity entity) throws ActionException {
        // 操作日志字符串
        StringBuilderExt builder = new StringBuilderExt();
        builder.format("保存冷藏冷柜信息，冷藏冷柜类型[{0}][{1}]，冷柜编码[{2}]，冷藏冷柜描述[{3}]，禁用状态值[{4}]，操作人员[{5}]"
                , String.valueOf(data.getEquipmentTypeCode()), dictionaryWrapper.getDataText(EDictCode.EQUIPMENT_TYPE, data.getEquipmentTypeCode())
                , data.getEquipmentCode(), data.getEquipmentDescribe(), String.valueOf(data.getDisableState()), userItem.getFullName());

        // 添加日志
        operationWrapper.operationLog(userItem, logTypeCode, builder.toString(), JacksonUtil.obj2Json(data), oldValue, JacksonUtil.obj2Json(entity));
    }

    /**
     * 更新冷藏冷柜信息
     *
     * @param userItem 当前帐号
     * @param data     请求数据
     * @return
     * @author LiCongLu
     * @date 2020-03-11 11:23
     */
    private void updateEquipment(UserItem userItem, EquipmentSaveData data) throws ActionException {
        // 验证主键和数据版本是否存在
        if (DataUtil.isNull(data.getId(), data.getVersion())) {
            throw exception("请求冷藏冷柜主键与冷藏冷柜版本号不能为空");
        }

        // 通过主键获取冷藏冷柜信息
        ColdStorageEquipmentEntity entity = coldStorageEquipmentMapper.getColdStorageEquipmentById(data.getId());
        if (DataUtil.isNull(entity) || DataUtil.isNull(entity.getId(), entity.getVersion())) {
            throw exception("冷藏冷柜主键错误，不存在此冷藏冷柜信息");
        }

        // 验证信息版本
        if (!DataUtil.equals(data.getVersion(), entity.getVersion())) {
            throw exception(versionError("冷藏冷柜信息"));
        }

        // 记录旧数据
        String oldValue = JacksonUtil.obj2Json(entity);

        // 覆盖数据
        BeanUtil.copy2Bean(data, entity);

        // 对冷藏冷柜信息进行判断处理
        checkEquipmentValue(entity);

        // 更新冷藏冷柜信息
        coldStorageEquipmentMapper.updateColdStorageEquipment(entity);

        // 添加操作日志
        saveEquipmentLog(userItem, operationLogCode.getUpdate(), data, oldValue, entity);
    }

    /**
     * 删除指定id的冷藏冷柜信息记录
     *
     * @param userItem 当前帐号
     * @param data     主键和版本号
     * @return
     * @author LiCongLu
     * @date 2020-03-10 16:33
     */
    @Transactional(rollbackFor = Exception.class)
    public BaseResult deleteEquipmentWithId(UserItem userItem, ArrayList<IdVersionData> data) throws ActionException {
        // 判断删除主键集合是否存在
        if (DataUtil.invalid(data)) {
            throw exception("不存在要删除的冷藏冷柜信息");
        }

        // 验证主键是否重复
        if (data.size() != getRepeatIdSize(data)) {
            throw exception("冷藏冷柜主键存在重复");
        }

        // 记录冷藏冷柜信息集合
        ArrayList<EquipmentEditItem> loadItems = new ArrayList<>();

        // 进行遍历删除信息
        for (IdVersionData idData : data) {
            // 通过主键查询冷藏冷柜信息
            EquipmentEditItem loadItem = equipmentDao.getEquipmentEditById(idData.getId());
            if (DataUtil.isNull(loadItem) || DataUtil.isNull(loadItem.getId(), loadItem.getVersion())) {
                throw exception("主键错误，不存在此冷藏冷柜信息");
            }

            // 验证冷藏冷柜信息版本
            if (!DataUtil.equals(loadItem.getVersion(), idData.getVersion())) {
                throw exception(versionError("冷藏冷柜信息"));
            }

            // 删除冷藏冷柜信息
            coldStorageEquipmentMapper.deletedForColdStorageEquipment(loadItem.getId(), userItem.getId(), loadItem.getVersion());
            // 记录冷藏冷柜信息
            loadItems.add(loadItem);
        }

        // 添加操作日志信息
        deleteEquipmentLog(userItem, operationLogCode.getDelete(), data, loadItems);

        return success("删除成功");
    }

    /**
     * 添加修改记录
     *
     * @param userItem    当前帐号
     * @param logTypeCode 操作日志值
     * @param data        请求数据
     * @param loadItems   删除信息实体
     * @return
     * @author LiCongLu
     * @date 2020-03-10 17:00
     */
    private void deleteEquipmentLog(UserItem userItem, Integer logTypeCode, ArrayList<IdVersionData> data, ArrayList<EquipmentEditItem> loadItems) throws ActionException {
        // 操作日志字符串
        StringBuilderExt builder = new StringBuilderExt();
        builder.format("删除冷藏冷柜信息，操作人员[{1}]", userItem.getFullName());
        // 添加日志
        operationWrapper.operationLog(userItem, logTypeCode, builder.toString(), JacksonUtil.obj2Json(data), JacksonUtil.obj2Json(loadItems), null);
    }
}
